package com.sjsu.aws.configurationMgmt.test;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import org.apache.log4j.Logger;
import com.sjsu.aws.configurationMgmt.ConfigMgmt;
import com.sjsu.aws.configurationMgmt.ConfigMgmtServiceImpl;
import com.sjsu.aws.configurationMgmt.Watcher;
import com.sjsu.aws.configurationMgmt.WatcherRegisterServiceImpl;

/**
 * 
 * @author Pawar Deepali
 * 
 */
public class ConfigurationUpdater {
	private final static Logger	                  LOG	      = Logger.getLogger(ConfigurationUpdater.class);
	
	private final static ScheduledExecutorService	scheduler	= Executors
	                                                                  .newScheduledThreadPool(1);
	public static int	                          i	          = 9;
	
	public static void main(String[] args) throws Exception {
		ConfigurationUpdater configurationUpdater = new ConfigurationUpdater();
		long pollingPeriod = 10000;
		String configName = "cfgd12";
		configurationUpdater.startPolling(pollingPeriod, configName);
	}
	
	public void startPolling(long pollingPeriod, String configName)
	        throws Exception {
		LOG.info("Start Configuration Updater");
		ConfigMgmtServiceImpl cfgService = new ConfigMgmtServiceImpl();
		pollDB(pollingPeriod, configName, cfgService);
	}
	
	public void pollDB(long pollingPeriod, final String configName,
	        final ConfigMgmtServiceImpl cfgService) {
		final Runnable watcher = new Runnable() {
			public void run() {
				System.out
				        .println("Updating Configuration Management Table...");
				WatcherRegisterServiceImpl watcherRegisterServiceImpl;
				
				try {
					ConfigMgmt cfg = new ConfigMgmt();
					cfg.setConfigId(configName);
					cfg.setDataDir("/dir" + i++ + "");
					cfgService.updateConfig(cfg);
					watcherRegisterServiceImpl = new WatcherRegisterServiceImpl();
					List<Watcher> registeredWatcherList = watcherRegisterServiceImpl
					        .getRegisteredWatcherList();
					LOG.info(registeredWatcherList.size());
					
					// start polling registered watchers
					LOG.info(registeredWatcherList.size());
					for (Watcher watcher : registeredWatcherList) {
						watcher.setWatchFlag("true");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		
		final ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate(
		        watcher, 0, pollingPeriod, MILLISECONDS);
		
	}
}
